#!/usr/bin/env python
# coding:utf-8

#
# 讓聚會前將 wikidot 頁面準備好
# 請加入星期三的排程 :)
#

# Author: 幸延 <a0726h77@gmail.com>
# Copyright: 幸延 <a0726h77@gmail.com>
# License: MIT

import sys
from xmlrpclib import ServerProxy
from common import *

read_settings_from_file()
api_user = volatile_settings['wikidot_api_user']
api_key = volatile_settings['wikidot_api_key']

s = ServerProxy('https://' + api_user + ':' + api_key + '@www.wikidot.com/xml-rpc-api.php')

tomorrow = thisThursday()

if sys.argv.__len__() == 2:
    tomorrow = sys.argv[1]

if isThursday(tomorrow) is False:
    print "Error: ", tomorrow, " is not Thursday..."
    exit()

lastweek = prevThursday(tomorrow)
nextweek = nextThursday(tomorrow)
site = 'hackingthursday'
page = tomorrow
title = tomorrow + ' 聚會手記'
content = '''
[[[ %s |上一週]]] || [[[ %s |下一週]]]

[[toc]]

[[html]]
<iframe src='http://pad.hackingthursday.org?showControls=true&showChat=true&showLineNumbers=true&useMonospaceFont=false' width=675 height=400></iframe>
[[/html]]
''' % (lastweek, nextweek)

s.pages.save_one({'site': site, 'page': page, 'title': title, 'content': content})

print 'To view : http://%s.wikidot.com/%s' % (site, page)


site = "hackingthursday"
page2 = "nav:top"
target_keyword = u"\n* [# 聚會手記] \n"

nav_top_page = s.pages.get_one({"site": site, "page": page2})
nav_top_content = nav_top_page["content"]

foundReturn = nav_top_content.find(tomorrow)
if foundReturn < 0:
    k_start = nav_top_content.find(target_keyword)
    if k_start >= 0:
        k_end = k_start + target_keyword.__len__()

        new_nav_top_content = nav_top_content[0:k_end] + u" * [[[" + tomorrow + "]]]\n" + nav_top_content[k_end:]

        #print new_nav_top_content
        s.pages.save_one({'site': site, 'page': page2, 'content': new_nav_top_content})
else:
    print "頁面的對應選單項目已建立"

print 'To view : http://%s.wikidot.com/%s' % (site, page2)
